const defaultAvatarUrl = 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0'

Page({

  /**
   * 页面的初始数据
   */
  data: {
    avatarUrl: defaultAvatarUrl,
    dialogues: null,
    nowDialogues:{
        id: -1,
        messages: []
    },
    selectedIndex:0,
    selectedTitle:'新对话',
    dialoguesSelectList:['新对话'],
    input_message:''
  },

  getUserAllDialogue:function () {
      wx.request({
        url: getApp().globalData.serverUrl+'/chat/chat/getUserAllDialogue',
        method:"GET",
        data:{
            userid:getApp().globalData.user.userid,
        },
        success:res=>{
            var dia_data=res.data.data
            for(var i=0;i<dia_data.length;i++){
                dia_data[i].messages=JSON.parse(dia_data[i].messages)
                console.log(dia_data[i].messages[0])
            }

            this.setData({
                dialogues:dia_data
            })

            this.setSelectList(dia_data)
        }
      })
  },

  getUserAllDialogueWithCallBack:function (callback) {
    wx.request({
      url: getApp().globalData.serverUrl+'/chat/chat/getUserAllDialogue',
      method:"GET",
      data:{
          userid:getApp().globalData.user.userid,
      },
      success:res=>{
          var dia_data=res.data.data
          for(var i=0;i<dia_data.length;i++){
              dia_data[i].messages=JSON.parse(dia_data[i].messages)
              console.log(dia_data[i].messages[0])
          }

          this.setData({
              dialogues:dia_data
          })

          this.setSelectList(dia_data)
          callback()
      }
    })
},

  setSelectList:function (dia_data) {
      var selectArray=['新对话']
      for(var i=0;i<dia_data.length;i++){
          selectArray.push(dia_data[i].messages[0].content)
      }
      this.setData({
          dialoguesSelectList:selectArray
      })
  },

  pickerChange:function (e) {
      var index=e.detail.value
      var dialogues=this.data.dialogues
      this.setData({
        selectedTitle:this.data.dialoguesSelectList[index],
      })
      if(index!=0){
          var oid=this.data.nowDialogues.id
          var omessages=this.data.nowDialogues.messages
          var dialogues=this.data.dialogues
          for(var i=0;i<dialogues.length;i++){
              if(oid==dialogues[i].id){
                  dialogues[i].messages=omessages
                  this.setData({
                      dialogues:dialogues
                  })
                  break;
              }
          }
          this.setData({
            nowDialogues:{
                id:dialogues[index-1].id,
                messages:this.data.dialogues[index-1].messages
            }
          })
      }else{
          this.setData({
            nowDialogues:{
                id:-1,
                messages:[]
            }
          })
      }
      console.log(this.data.nowDialogues.messages)
  },

  sendButtonOnClick:function () {
      var message=this.data.input_message

      var new_user_message={
          "role":"user",
          "content":message
      }
      var new_assistant_message={
        "role":"assistant",
        "content":""
      }
      var now_messages=this.data.nowDialogues.messages
      now_messages.push(new_user_message)
      now_messages.push(new_assistant_message)
      var ndid=this.data.nowDialogues.id
      this.setData({
          nowDialogues:{
              id:ndid,
              messages:now_messages
          }
      })

      this.send(message)
  },

  send:function (message) {
      var userid=getApp().globalData.user.userid
      var model='yi-spark'
      console.log(this.data.nowDialogues)
      var dialogueid=this.data.nowDialogues.id
      if(userid==null)return

      console.log("发送消息:"+message+" 对话id:"+dialogueid+" 用户id:"+userid)

      const requestTask = wx.request({
        url: getApp().globalData.serverUrl+'/chat/chat/sendMessage',
        method:"POST",
        // responseType: "arraybuffer",
        enableChunked: true, //关键！开启流式传输模式
        dataType:"json",
        data:{
            "message":message+'',
            "model":model+'',
            "userid":userid,
            "dialogueid":dialogueid
        },
        success: (res) => {
            console.log("结束----request success", res);
        },
        fail: (err) => {
            console.log("request fail", err);
          }
      })

      // 监听请求头接受事件
    requestTask.onHeadersReceived(r => {
    });

    // 监听数据分块接收事件
    requestTask.onChunkReceived((res) => {
        res.data=this.arrayBuffer2String(res.data)
        var data_texts=res.data.split('data:{')
        data_texts.splice(0, 1);
        var data_jsons=[]
        for(var i=0;i<data_texts.length;i++){
            data_texts[i]='{'+data_texts[i]
            
            var text=data_texts[i]
            while(text.length!=0){
                if(text[text.length-1]!='}'){
                    text=text.slice(0,-1)
                }else{
                    console.log("触发裁剪:"+text)
                    data_texts[i]=text
                    break;
                }
            }

            console.log(data_texts[i])
            try{
                data_jsons.push(JSON.parse(data_texts[i]))
            }catch(err){}
        }
        for(var i=0;i<data_jsons.length;i++){
            if(data_jsons[i].data!="[DONE]"){
                data_jsons[i].data=JSON.parse(data_jsons[i].data)
            }
        }

        for(var i=0;i<data_jsons.length;i++){
            if(data_jsons[i].data!="[DONE]"){
                var now_messages=this.data.nowDialogues.messages
                var new_assistant_message={
                    "role":"assistant",
                    "content":data_jsons[i].data.content
                }

                if(data_jsons[i].data.lastOne==true){
                    console.log("最后一条")
                    now_messages[now_messages.length-1]=new_assistant_message
                    var oid=this.data.nowDialogues.id
                    var ndid=data_jsons[i].data.dialogueid
                    this.setData({
                        nowDialogues:{
                            id:ndid,
                            messages:now_messages
                        }
                    })
                    console.log("检查是否是新对话:"+oid+" "+ndid)
                    if(oid!=ndid){
                        console.log("触发替换对话:"+oid+" "+ndid)
                        this.leaveNewDialogue(ndid)
                    }
                }else{
                    now_messages[now_messages.length-1]=new_assistant_message
                    var ndid=this.data.nowDialogues.id
                    this.setData({
                        nowDialogues:{
                            id:ndid,
                            messages:now_messages
                        }
                    })
                }
            }
        }
    });
  },

  leaveNewDialogue:function (ndid) {
      this.getUserAllDialogueWithCallBack(()=>{
        var index=0
        var dialogues=this.data.dialogues
        for(var i=0;i<dialogues.length;i++){
            if(dialogues[0].id==ndid)break
            else index+=1
        }
        index+=1
        console.log(index)
        this.setData({
            selectedIndex:index,
            selectedTitle:this.data.dialoguesSelectList[index]
        })
      })
  },

  BindUserInput:function (e) {
    this.setData({
        input_message:e.detail.value
    })
  },

  arrayBuffer2String:function (buffer) {
    let  encodedString = String.fromCodePoint.apply(null, new Uint8Array(buffer));
    let decodedString = decodeURIComponent(escape(encodedString));//没有这一步中文会乱码
    return decodedString
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
      this.getUserAllDialogue()
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})